﻿/*
 * -----------------------------------------------------------
 * All Rights Reserved , Copyright (C) 2014 , WD , Ltd. 
 *
 * Author: ching
 * Date: 2014-9-29
 * Version: V1.0
 * Description: 摄像头操作帮助类
 * 
 *
 * -----------------------------------------------------------
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;
using System.Drawing;
using System.Drawing.Imaging;

using AForge.Video;
using AForge.Video.DirectShow;
using System.Collections;
using AForge.Video.FFMPEG;

namespace DGSY_V3MMS.FabricManage
{
    /// <summary>
    /// 视频摄像类(使用AForge)
    /// </summary>
    public class VideoHelper
    {
        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoSource;
        //private VideoCapabilities[] snapshotCapabilities;
        public string g_s_Path = AppDomain.CurrentDomain.BaseDirectory + "Capture\\ManualSave\\";
        public int selectedDeviceIndex = 0;
        //public VideoCapabilities videoCapability;

        #region 摄像头操作方法

        /// <summary>
        /// 获取所有摄像头设备
        /// </summary>
        /// <returns></returns>
        public FilterInfoCollection GetDevices()
        {
            try
            {
                //枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if (videoDevices.Count != 0)
                {
                    // LogHelper.WriteFile("已找到视频设备.");
                    return videoDevices;
                }
                else
                    return null;
            }
            catch 
            {
                // LogHelper.WriteFile("error:没有找到视频设备！具体原因：" + ex.Message);
                return null;

            }
        }

        /// <summary>
        /// 连接视频摄像头
        /// </summary>
        /// <param name="deviceIndex"></param>
        /// <param name="resolutionIndex"></param>
        /// <returns></returns>
        public VideoCaptureDevice VideoConnect(int deviceIndex)//= 0), int resolutionIndex = 0)
        {
            if (videoDevices.Count <= 0)
                return null;
            selectedDeviceIndex = deviceIndex;
            videoSource = new VideoCaptureDevice(videoDevices[deviceIndex].MonikerString);

            //videoSource.DesiredFrameSize = new Size(500, 300);
            //videoSource.DesiredFrameRate = 1;

            //snapshotCapabilities = videoSource.SnapshotCapabilities;
            //videoSource.ProvideSnapshots = true;
            //videoSource.SnapshotResolution = snapshotCapabilities[resolutionIndex];
            //videoSource.SnapshotFrame += new AForge.Video.NewFrameEventHandler(videoSource_SnapshotFrame);

            return videoSource;
        }

        /// <summary>
        /// 抓图，拍照，单帧
        /// </summary>
        public void GrabBitmap(string path)
        {
            if (videoSource == null)
                return;
            g_s_Path = path;
            videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
        }

        /// <summary>
        /// 连续拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
            //string fullPath = path + "temp\\";
            //if (!Directory.Exists(fullPath))
            //    Directory.CreateDirectory(fullPath);
            //string img = fullPath + DateTime.Now.ToString("yyyyMMdd hhmmss") + ".bmp";
            bmp.Save(g_s_Path);
            videoSource.NewFrame -= new NewFrameEventHandler(videoSource_NewFrame);
        }

        /// <summary>
        /// 关闭视频连接
        /// </summary>
        //public void CloseVideo()
        //{
        //    //
        //}

        private void DoWork()
        {
            videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
            if (videoSource == null)
                return;

            videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
        }

        /// <summary>
        /// 录像
        /// </summary>
        /// <param name="savePath"></param>
        public void Videotape(string savePath)
        {
            //
        }


        private bool stopREC = true;
        private bool createNewFile = true;
        private string videoFileFullPath = string.Empty;  //视频文件全路径
        private string videoPath = AppDomain.CurrentDomain.BaseDirectory + "Video\\"; //视频文件路径
        private VideoFileWriter videoWriter = null;
        private string videoFileName = string.Empty;  //视频文件名
        private string drawDate = string.Empty;  //绘制日期
        private int frameRate = 20;  //默认帧率

        //这个事件是控件videoSourcePlayer1的videoSourcePlayer1_NewFrame事件
        /// <summary>
        /// 这个事件是控件videoSourcePlayer1的videoSourcePlayer1_NewFrame事件，
        /// 事件是自动触发的，只要控制什么录制什么时候结束即可
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="image"></param>
        private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
        {
            //录像
            //给屏幕的左上角写上时间
            Graphics g = Graphics.FromImage(image);
            SolidBrush drawBrush = new SolidBrush(Color.Yellow);
            Font drawFont = new Font("Arial", 6, FontStyle.Bold, GraphicsUnit.Millimeter);
            int xPos = image.Width - (image.Width - 15);
            int yPos = 10;
            //写到屏幕上的时间
            drawDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            g.DrawString(drawDate, drawFont, drawBrush, xPos, yPos);

            if (!Directory.Exists(videoPath))
                Directory.CreateDirectory(videoPath);

            //创建文件路径
            //fileFullPath = path + fileName;

            if (stopREC)
            {
                stopREC = true;
                createNewFile = true;  //这里要设置为true表示要创建新文件
                if (videoWriter != null)
                    videoWriter.Close();
            }
            else
            {
                //开始录像
                if (createNewFile)
                {
                    videoFileName = DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss") + ".avi";
                    videoFileFullPath = videoPath + videoFileName;
                    createNewFile = false;
                    if (videoWriter != null)
                    {
                        videoWriter.Close();
                        videoWriter.Dispose();
                    }
                    videoWriter = new VideoFileWriter();
                    //这里必须是全路径，否则会默认保存到程序运行根据录下
                    videoWriter.Open(videoFileFullPath, image.Width, image.Height, frameRate, VideoCodec.MPEG4);
                    videoWriter.WriteVideoFrame(image);
                }
                else
                {
                    videoWriter.WriteVideoFrame(image);
                }
            }
        }


        #endregion


        //
    }
}
